from typing import Dict, Optional
from datetime import datetime, timezone
from flask_jwt_extended import create_access_token, create_refresh_token
from ..models.user import User
from ..extensions.extensions import db

class AuthService:
    @staticmethod
    def login(username: str, password: str) -> Optional[Dict]:
        """
        用户登录
        :param username: 用户名
        :param password: 密码
        :return: 包含token的字典或None
        """
        user = User.query.filter_by(username=username, deleted=False).first()
        if user and user.verify_password(password):
            if not user.status:
                return None, "账户已被禁用"
                
            # 创建访问令牌和刷新令牌
            access_token = create_access_token(identity=user.id)
            refresh_token = create_refresh_token(identity=user.id)
            
            # 更新登录信息
            user.last_login_time = datetime.now(timezone.utc)
            db.session.commit()
            
            return {
                "access_token": access_token,
                "refresh_token": refresh_token,
                "token_type": "Bearer"
            }, "登录成功"
            
        return None, "用户名或密码错误"

    @staticmethod
    def get_user_info(user_id: int) -> Optional[Dict]:
        """
        获取用户信息
        :param user_id: 用户ID
        :return: 用户信息字典
        """
        user = User.query.filter_by(id=user_id, deleted=False).first()
        if not user:
            return None
            
        return {
            "id": user.id,
            "username": user.username,
            "real_name": user.real_name,
            "avatar": user.avatar,
            "email": user.email,
            "mobile": user.mobile,
            "status": user.status,
            "dept_id": user.dept_id,
            "last_login_time": user.last_login_time.strftime('%Y-%m-%d %H:%M:%S') if user.last_login_time else None,
            "last_login_ip": user.last_login_ip
        }

    @staticmethod
    def refresh_token(user_id: int) -> Dict:
        """
        刷新访问令牌
        :param user_id: 用户ID
        :return: 新的访问令牌
        """
        access_token = create_access_token(identity=user_id)
        return {
            "access_token": access_token,
            "token_type": "Bearer"
        } 